package com.lipp.luosu.test.efftiveJava.asyc;

/**
 * @ClassNameCountDownLatchDemo
 * @description: TODO 类描述
 * @Author lipp
 * @Date 2024/2/2 14:16
 * @Version 1.0
 */
import java.util.concurrent.CountDownLatch;

public class CountDownLatchDemo {

    public static void main(String[] args) throws InterruptedException {
        int totalTasks = 5;
        CountDownLatch latch = new CountDownLatch(totalTasks);

        for (int i = 0; i < totalTasks; i++) {
            int finalI = i;
            new Thread(() -> {
                executeTask(finalI);
                latch.countDown(); // 完成一个任务后计数减一
            }).start();
        }



        // 主线程等待所有子线程完成任务
        latch.await();
        long count = latch.getCount();
        System.out.println(count);
        System.out.println("All tasks have been completed.");
    }

    private static void executeTask(int taskId) {
        System.out.println("Task " + taskId + " started by " + Thread.currentThread().getName());
        try {
            Thread.sleep(1000); // 模拟耗时操作
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        System.out.println("Task " + taskId + " completed by " + Thread.currentThread().getName());
    }
}
